<template>
    <el-row class="flex items-stretch">
        <el-col :span="21" class="flex flex-wrap content-center">
            <component-page-loading :status="userListStatus" v-if="['loading', 'error'].indexOf(userListStatus) >= 0" @reload="getUsers"></component-page-loading>
            <component-page-loading status="nodata" v-else-if="!userList.length"></component-page-loading>
            <div class="nub-list" v-else>
                <div class="nub-item" v-for="(item, index) in userList" :key="index">
                    <div class="nub-icon icon-user">
                        <font-awesome-icon icon="user-tie"></font-awesome-icon>
                    </div>
                    <div class="nub-text">{{ item.account_id }}</div>
                </div>
            </div>
        </el-col>
        <el-col :span="3" class="text-right" v-if="userListStatus == 'dle'">
            <el-button type="text" @click="dialogVisible = true">{{ $t('action.select') }}</el-button>
        </el-col>
        <el-dialog :title="$t('game.user.dialog.selection')" width="650px" :visible.sync="dialogVisible" append-to-body>
            <div v-loading="loading">
                <div class="pb-4">
                    <div v-if="!userListCache.length">
                        <component-page-loading status="nodata"></component-page-loading>
                    </div>
                    <div class="nub-list" v-else>
                        <div class="nub-item" v-for="(item, index) in userListCache" :key="index">
                            <div class="nub-icon icon-user">
                                <font-awesome-icon icon="user-tie"></font-awesome-icon>
                            </div>
                            <div class="nub-text">{{ item.account_id }}</div>
                            <div class="nub-close" @click="tagCheckedDelete(item, index)">
                                <i class="el-icon-close"></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="pb-4">
                    <el-input :placeholder="$t('form.inputPlaceholder')" v-model="filterOption.keyword" class="input-search-select" clearable @change="filterChange">
                        <el-select slot="prepend" v-model="filterOption.keyword_column">
                            <el-option label="UID" value="id"></el-option>
                            <el-option :label="$t('game.user.account_id')" value="account_id"></el-option>
                        </el-select>
                        <el-button slot="append" icon="el-icon-search" @click="filterChange"></el-button>
                    </el-input>
                </div>
                <el-table ref="multipleTable" style="width: 100%"
                          :data="dataList"
                          @row-click="handleRowClick"
                          @select="handleSelection"
                          @select-all="handleSelectionAll">
                    <el-table-column min-width="80" type="selection"></el-table-column>
                    <el-table-column min-width="150" label="UID" prop="id">
                        <template slot-scope="scope">
                            <div v-if="scope.column.property != filterOption.keyword_column">{{ scope.row.id }}</div>
                            <div v-else v-html="$options.filters.hsFilterKeyword(scope.row.id, filterOption.keyword)"></div>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="200" :label="$t('game.user.account_id')" prop="account_id">
                        <template slot-scope="scope">
                            <div v-if="scope.column.property != filterOption.keyword_column">{{ scope.row.account_id }}</div>
                            <div v-else v-html="$options.filters.hsFilterKeyword(scope.row.account_id, filterOption.keyword)"></div>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="200" :label="$t('platform.setting.tree.org')" prop="plat_code">
                        <template slot-scope="scope">{{ scope.row.org.name || scope.row.plat_code }}</template>
                    </el-table-column>
                </el-table>
                <div class="pt-2 text-right" v-if="dataMeta.total">
                    <el-pagination background layout="prev, pager, next"
                                   :current-page="filterOption.page"
                                   :page-size="filterOption.page_size"
                                   :total="dataMeta.total"
                                   @current-change="filterPageChange">
                    </el-pagination>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{ $t('action.cancel') }}</el-button>
                <el-button type="primary" @click="onSubmit">{{ $t('action.confirm') }}</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>

<script>
export default {
    name: "PageSelectionUsers",
    model: {
        prop: 'ids',
        event: 'change'
    },
    props: {
        ids: {
            type: Array,
            default: () => []
        },
    },
    data() {
        return {
            userListStatus: 'dle',
            userList: [],
            userListCache: [],
            dialogVisible: false,
            loading: false,
            filterOption: {
                keyword: '',
                keyword_column: 'id',
                page: 1,
                page_size: 5,
            },
            dataMeta: {
                total: 0,
            },
            dataList: []
        }
    },
    watch: {
        ids: {
            immediate: true,
            handler(n, o) {
                // 获取已选用户
                this.getUsers();
            }
        },
        dialogVisible: function (n, o) {
            if (n) {
                // 初始化选中数据
                this.userListCache = _.cloneDeep(this.userList);
                // 初始化数据列表
                this.filterChange();
            } else {
                // 初始化表格参数
                this.clearFilterOption();
            }
        }
    },
    methods: {
        // 获取已选用户
        getUsers() {
            if (_.isEqual(this.ids, _.map(this.userList, 'id'))) {
                return
            }
            if (!this.ids.length) {
                this.userList = [];
                return
            }
            this.userListStatus = 'loading';
            axios.get('/common/getUsers', {
                params: {
                    ids: this.ids
                }
            }).then((response) => {
                if (response.data.resp_msg.code == 200) {
                    this.userList = response.data.resp_data;
                    this.userListStatus = 'dle';
                } else {
                    this.userListStatus = 'error';
                }
            })
        },
        clearFilterOption() {
            this.filterOption.keyword = '';
            this.filterOption.page = 1;
            this.dataMeta.total = 0;
            this.dataList = [];
        },
        filterChange() {
            this.filterOption.page = 1;
            this.getDataList();
        },
        filterPageChange(page) {
            this.filterOption.page = page;
            this.getDataList();
        },
        getDataList() {
            this.loading = true;
            axios.get('/common/getUserList', {
                params: this.filterOption
            }).then((response) => {
                if (response.data.resp_msg.code == 200) {
                    this.dataMeta = response.data.resp_data.meta;
                    this.dataList = response.data.resp_data.data;
                    // 初始化选中表格
                    this.$nextTick(function () {
                        this.$refs.multipleTable.clearSelection();
                        // 初始化表格选中
                        for (let i in this.dataList) {
                            for (let j in this.userListCache) {
                                if (this.userListCache[j].id == this.dataList[i].id) {
                                    this.$refs.multipleTable.toggleRowSelection(this.dataList[i]);
                                    break;
                                }
                            }
                        }
                    });
                } else {
                    this.$message({
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                        message: this.$t('messages.failed', {status: this.$t('action.search')}) + `<div class="mt-2">${response.data.resp_msg.message}</div>`,
                        showClose: true
                    });
                }
                this.loading = false;
            })
        },
        onSubmit() {
            // 关闭模态框
            this.dialogVisible = false;
            // 同步数据
            this.userList = _.cloneDeep(this.userListCache);
            // 对外广播事件
            this.$emit('change', _.map(this.userList, 'id'));
        },
        // 标签删除已选用户
        tagCheckedDelete(data, index) {
            this.userListCache.splice(index, 1);
            for (let i in this.dataList) {
                if (this.dataList[i].id == data.id) {
                    this.$refs.multipleTable.toggleRowSelection(this.dataList[i]);
                    break;
                }
            }
        },
        // 表格选择点击用户
        handleRowClick(row) {
            this.$refs.multipleTable.toggleRowSelection(row);
            // 处理选中数据
            this.handleSelection(null, row);
        },
        // 表格选择或取消选中用户
        handleSelection(selection, row) {
            for (let i in this.userListCache) {
                if (this.userListCache[i].id == row.id) {
                    this.userListCache.splice(i, 1);
                    return;
                }
            }
            this.userListCache.push(row);
        },
        // 表格选择或取消选中用户【全选】
        handleSelectionAll(selection) {
            if (_.isEmpty(selection)) {
                for (let item of this.dataList) {
                    for (let i in this.userListCache) {
                        if (this.userListCache[i].id == item.id) {
                            this.userListCache.splice(i, 1);
                            break;
                        }
                    }
                }
            } else {
                for (let item of selection) {
                    let isExists = false;
                    for (let i in this.userListCache) {
                        if (this.userListCache[i].id == item.id) {
                            isExists = true;
                            break;
                        }
                    }
                    if (!isExists) {
                        this.userListCache.push(item);
                    }
                }
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.nub-list .nub-item {
    margin-top: 3px;
    margin-right: 6px;
    margin-bottom: 3px;
}

::v-deep .el-dialog__body {
    min-height: 450px;
    padding-top: 12px;
    padding-bottom: 15px;
}
</style>
